from django.shortcuts import *
from django.http import HttpResponse
from .models import *


# 原生上传
# def index(request):
#     if request.method == 'GET':
#         return render(request,'index.html')
#     elif request.method =='POST':
#         name = request.POST.get('username','')
#         photo = request.FILES.get('photo','')
#         import os
#         if not os.path.exists('migar'):
#             os.makedirs('migar')
#
#         with open(os.path.join(os.getcwd(),'migar',photo.name),'wb') as f:
#             # f.write(photo.read())  #一次性读取并写入内存,如果文件大,则不适用
#             photo.chunks() #分块写入
#             for n in photo.chunks():
#                 f.write(n)
#
#
#         return HttpResponse('上传成功')
#     else:
#         return HttpResponse('错误楼')
# django文件上传
def index(request):
    if request.method == 'GET':
        return render(request, 'index.html')
    else:
        name = request.POST.get('username', '')
        photo = request.FILES.get('photo', '')
        #入库操作
        Stus.objects.create(name=name, photo=photo)
        return redirect(reverse('show'))

#显示图片
def show(request):
    #读取`所有学生信息
    1/0
    stu=Stus.objects.all()
    return render(request,'show.html',{'stu':stu})

#下载图片
def dow(request):
    #获取图片地址
    photo = request.GET.get('photo','')
    #获取图片文件名(从右/的后面开始切)
    filename = photo[photo.rindex("/")+1:]
    # print(photo)
    # print(filename)
    #开启一个流
    import os
    path = os.path.join(os.getcwd(),'migar',photo)
    # print(path)
    with open(path,'rb') as f:
        response = HttpResponse(f.read())
        # response['Content-Type'] = 'imgar/png'
        response['Content-Disposition']='attachment;filename='+filename

    return response

